What could be easier than comparing integer numbers? However, the given piece of code doesn't recognize some of the special numbers for a reason to be found. Your task is to find the bug and eliminate it.
使用下列函式比較數字時,(* 42 42)
並沒有回傳 everything squared
,要修掉 bug
(ns how-do-i-compare)
(defn what-is [x]
(cond
(identical? x 42) "everything"
(identical? x (* 42 42)) "everything squared"
:else "nothing"))
(ns how-do-i-compare-test
(:require [clojure.test :refer :all]
[how-do-i-compare :refer [what-is]]))
(deftest tests
(are [x answer] (= (what-is x) answer)
0 "nothing"
123 "nothing"
-1 "nothing"
42 "everything"
(* 42 42) "everything squared"
))
identical?
判斷兩個參數是否為同一個 object; =
判斷兩個是否有一樣的值
(ns how-do-i-compare)
(defn what-is [x]
(cond
(= x 42) "everything"
(= x (* 42 42)) "everything squared"
:else "nothing"))
(def x 123)
(def y 123)
(= x y) ;; true
(identical? x y) ;; true
(= x x) ;; true
(identical? x x) ;; true
(= x 123) ;; true
(identical? x 123) ;; true
(def x "123")
(def y "123")
(= x y) ;; true
(identical? x y) ;; true
(def x (String. "123"))
(def y (String. "123"))
(= x y) ;; true
(identical? x y) ;; false
(def x (list 1 2 3))
(def y (list 1 2 3))
(= x y) ;; true
(identical? x y) ;; false